//
//  AdScrollView.m
//  MemberProject
//
//  Created by mac on 15/4/27.
//  Copyright (c) 2015年 MAC OS X. All rights reserved.
//

#import "AdScrollView.h"
#import "UIImageView+WebCache.h"
#import "AdScrollViewCollectionViewCell.h"
@interface AdScrollView ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property(strong,nonatomic)NSTimer *timer;
@property(strong,nonatomic)UIScrollView *scrollView;
@property(strong,nonatomic)UICollectionView *collectionView;
@end
@implementation AdScrollView
-(void)awakeFromNib{
    NSLog(@"%s",__func__);
}

-(void)dealloc{
    if([self.timer isValid]){
        [self.timer invalidate];
    }
    self.timer=nil;
}

-(instancetype)initWithFrame:(CGRect)frame{
    if(self=[super initWithFrame:frame]){
    
        UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init];
        layout.scrollDirection=UICollectionViewScrollDirectionHorizontal;
        layout.minimumInteritemSpacing=0;
        layout.minimumLineSpacing=0;
        UICollectionView *collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height) collectionViewLayout:layout];
        self.collectionView=collectionView;
        [self addSubview:collectionView];
        collectionView.delegate=self;
        collectionView.dataSource=self;
        collectionView.pagingEnabled=YES;
        collectionView.showsHorizontalScrollIndicator=NO;
        [collectionView registerNib:[UINib nibWithNibName:@"AdScrollViewCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CellIdentifier"];
        collectionView.backgroundColor=[UIColor clearColor];
//        self.scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
//        self.scrollView.delegate=self;
//        self.scrollView.pagingEnabled = YES;
//        self.scrollView.showsHorizontalScrollIndicator =NO;
//        [self addSubview:self.scrollView];
    }
    return self;
}

-(void)setFrame:(CGRect)frame{
    [super setFrame:frame];
    CGRect rect=self.collectionView.frame;
    rect.size=frame.size;
    self.collectionView.frame=rect;
}

-(void)setData:(NSArray *)data{
    _data=data;
    [self refresh];
}

-(void)refresh{
    if(self.data.count!=0){
//        [self.scrollView removeAllSubviews];
//        
//        
//        self.scrollView.contentSize=CGSizeMake(self.scrollView.width*self.data.count, self.scrollView.height);
//        self.scrollView.contentOffset=CGPointMake(self.scrollView.width, 0);
//        if([[self.data lastObject] isKindOfClass:[NSString class]]){
//            //字符串
//            for(int i=0;i<self.data.count;i++){
//                UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(i*self.scrollView.width, 0, self.scrollView.width, self.scrollView.height)];
//                [self.scrollView addSubview:imageView];
//                imageView.image=[UIImage imageNamed:self.data[i]];
//            }
//        }else{
//            //字典
//            for(int i=0;i<self.data.count;i++){
//                NSDictionary *dic=self.data[i];
//                UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(i*self.scrollView.width, 0, self.scrollView.width, self.scrollView.height)];
//                [self.scrollView addSubview:imageView];
//                imageView.tag=100+i;
//                imageView.userInteractionEnabled=YES;
//                [imageView sd_setImageWithURL:[NSURL URLWithString:dic[@""]]];
//                UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
//                [imageView addGestureRecognizer:tap];
//            }
//            
//        
//        }
        
        [self.collectionView reloadData];
        self.collectionView.contentOffset=CGPointMake(self.collectionView.width, 0);

        if([self.timer isValid]){
            [self.timer invalidate];
        }
        self.timer=[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
    }
}
#pragma mark - tap
-(void)tap:(UITapGestureRecognizer *)sender{
    UIView *view=sender.view;
    int index=(int)view.tag-100;
    NSDictionary *dic=self.data[index];
    if([self.delegate respondsToSelector:@selector(adScrollView:tapImageViewWithIndex:urlStr:)]){
        [self.delegate adScrollView:self tapImageViewWithIndex:index urlStr:dic[@""]];
    }
}

#pragma mark - timer
-(void)timer:(NSTimer *)sender{
    int nowPage=self.collectionView.contentOffset.x/self.collectionView.width;
    [self.collectionView setContentOffset:CGPointMake(self.collectionView.width*(nowPage+1), 0) animated:YES];
}


#pragma mark - scrollView
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if(scrollView==self.collectionView){
        if([self.timer isValid]){
            [self.timer invalidate];
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if(scrollView==self.collectionView){
        if([self.timer isValid]){
            [self.timer invalidate];
        }
        self.timer=[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if(scrollView==self.collectionView){
        if(scrollView.contentOffset.x>=scrollView.contentSize.width-scrollView.width){
            [scrollView setContentOffset:CGPointMake(scrollView.width, 0)];
            return;
        }
        if(scrollView.contentOffset.x<=0){
            [scrollView setContentOffset:CGPointMake(scrollView.contentSize.width-2*scrollView.width, 0)];
            return;
        }
        
    }
}

#pragma mark - collection
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.data.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier=@"CellIdentifier";
    AdScrollViewCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    NSDictionary *dic=self.data[indexPath.row];
    if(dic[@"link"]==nil){
        cell.imageView.image=[UIImage imageNamed:self.data[indexPath.row][@"image"]];
    }else{
        [cell.imageView sd_setImageWithURL:dic[@"image"] placeholderImage:nil];
    }
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(collectionView.width, collectionView.height);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    NSDictionary *dic=self.data[indexPath.row];
    if(dic[@"link"]){
        if([dic isKindOfClass:[NSDictionary class]]){
            if([self.delegate respondsToSelector:@selector(adScrollView:tapImageViewWithIndex:urlStr:)]){
                [self.delegate adScrollView:self tapImageViewWithIndex:indexPath.row urlStr:dic[@"link"]];
            }
        }
    }
    
}

-(void)refreshTimer{
    if([self.timer isValid]){
        [self.timer invalidate];
    }
    self.timer=[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
}

@end
